from nicegui import ui
import subprocess
import sys
import os

current_user = None

users_db = {
    'admin': 'password123',
    'user1': '123456',
    'demo': 'demo123'
}


def authenticate(username, password):
    return users_db.get(username) == password


@ui.page('/')
def login_page():
    ui.colors(primary='#1976d2')
    with ui.card().classes('absolute-center').style('width: 400px'):
        ui.label('性格分析系统登录').classes('text-2xl font-bold text-center mb-4')
        username_input = ui.input('用户名', placeholder='请输入用户名').classes('w-full')
        password_input = ui.input('密码', password=True, placeholder='请输入密码').classes('w-full')
        error_label = ui.label('').classes('text-red text-center')

        def handle_login():
            global current_user
            if authenticate(username_input.value, password_input.value):
                current_user = username_input.value
                ui.navigate.to('/dashboard')
            else:
                error_label.text = '用户名或密码错误'

        password_input.on('keydown.enter', handle_login)
        ui.button('登录', on_click=handle_login).classes('w-full bg-primary text-white')

        with ui.expansion('测试账户', icon='info').classes('w-full mt-4'):
            ui.label('admin / password123')
            ui.label('user1 / 123456')
            ui.label('demo / demo123')


@ui.page('/dashboard')
def dashboard():
    if not current_user:
        ui.navigate.to('/')
        return

    with ui.header().classes('bg-primary text-white'):
        ui.label('性格分析系统').classes('text-xl font-bold')
        with ui.row().classes('ml-auto'):
            ui.label(f'欢迎, {current_user}').classes('text-white')
            ui.button('退出', on_click=lambda: [setattr(globals(), 'current_user', None), ui.navigate.to('/')]).classes(
                'ml-2')

    with ui.column().classes('p-8'):
        ui.label('选择分析模块').classes('text-2xl font-bold mb-6')

        with ui.grid(columns=3).classes('gap-6 w-full'):
            # 基础分析
            with ui.card().classes('p-6 cursor-pointer hover:shadow-lg'):
                ui.icon('analytics', size='3rem').classes('text-blue-500 mb-4')
                ui.label('基础性格分析').classes('text-xl font-bold mb-2')
                ui.label('查看性格分布饼图和3D散点图').classes('text-gray-600 mb-4')
                ui.button('启动分析', on_click=lambda: run_analysis('main.py')).classes('w-full bg-blue-500 text-white')

            # 数据概览
            with ui.card().classes('p-6 cursor-pointer hover:shadow-lg'):
                ui.icon('table_chart', size='3rem').classes('text-green-500 mb-4')
                ui.label('数据概览分析').classes('text-xl font-bold mb-2')
                ui.label('查看数据集基本信息和统计').classes('text-gray-600 mb-4')
                ui.button('启动分析', on_click=lambda: run_analysis('二维.py')).classes(
                    'w-full bg-green-500 text-white')

            # 详细分析
            with ui.card().classes('p-6 cursor-pointer hover:shadow-lg'):
                ui.icon('scatter_plot', size='3rem').classes('text-purple-500 mb-4')
                ui.label('详细数据分析').classes('text-xl font-bold mb-2')
                ui.label('自定义轴的3D散点图分析').classes('text-gray-600 mb-4')
                ui.button('启动分析', on_click=lambda: run_analysis('c.py')).classes('w-full bg-purple-500 text-white')

            # PCA分析
            with ui.card().classes('p-6 cursor-pointer hover:shadow-lg'):
                ui.icon('psychology', size='3rem').classes('text-orange-500 mb-4')
                ui.label('PCA降维分析').classes('text-xl font-bold mb-2')
                ui.label('主成分分析降维可视化').classes('text-gray-600 mb-4')
                ui.button('启动分析', on_click=lambda: run_analysis('d.py')).classes('w-full bg-orange-500 text-white')

            # 高级降维
            with ui.card().classes('p-6 cursor-pointer hover:shadow-lg'):
                ui.icon('hub', size='3rem').classes('text-red-500 mb-4')
                ui.label('高级降维分析').classes('text-xl font-bold mb-2')
                ui.label('t-SNE和UMAP降维分析').classes('text-gray-600 mb-4')
                ui.button('启动分析', on_click=lambda: run_analysis('e.py')).classes('w-full bg-red-500 text-white')


def run_analysis(script_name):
    """在新端口启动分析脚本"""
    try:
        # 获取下一个可用端口
        port = get_next_port()

        # 启动新的分析程序
        subprocess.Popen([
            sys.executable, script_name, '--port', str(port)
        ], cwd=os.getcwd())

        # 显示提示信息
        ui.notify(f'正在启动{script_name}...', type='info')
        ui.notify(f'请在浏览器中访问: http://localhost:{port}', type='positive')

    except Exception as e:
        ui.notify(f'启动失败: {str(e)}', type='negative')


def get_next_port():
    """获取下一个可用端口"""
    import socket
    ports = [8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089, 8090]
    for port in ports:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(('localhost', port))
            sock.close()
            return port
        except:
            continue
    return 8091  # 默认端口


if __name__ in {"__main__", "__mp_main__"}:
    ui.run(title='性格分析系统主控制台', port=8080, show=True)